import React from "react";
import { connect } from "react-redux";
import { Form, Input, Popover, Modal, Select, Radio, Tag } from "antd";
import menuRoute from "routes/menuRoute";
import contractService from "containers/contract/contract.service";
import "styles/contract/my-contract/my-contract.scss";
import moment from "moment";
import debounce from "lodash.debounce";
import contractStatus from "containers/contract/contract-status";
import { messages } from "share/common";
import AdvancedTable from "components/advanced-table";
import NumberRange from "../../financial-management/expense-view/component/number-range";
import { expensePartner } from "containers/financial-management/expense-view/component/func-component";
import openSlideFrame from "share/openSlideFrame";
import baseService from "share/base.service";

const Search = Input.Search;
const { Option } = Select;

class ContractView extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      searchForm: [
        {
          component: "Chooser",
          id: "contractTypeId",
          label: messages("finance-6.key79") /*合同类型*/,
          props: {
            single: true,
            labelKey: "contractTypeName",
            valueKey: "id",
            type: "contract_type",
            listExtraParams: { companyId: this.props.company.id },
          },
          parser: (value) => ({
            contractTypeId: value && value.length ? value[0].id : void 0,
          }),
        },
        {
          component: "Chooser",
          id: "companyId",
          dataIndex: "companyName",
          label: messages("finance-6.key53") /*合同公司*/,
          props: {
            type: "company",
            valueKey: "id",
            labelKey: "name",
            listExtraParams: { setOfBooksId: this.props.company.setOfBooksId },
            single: true,
          },
          parser: (value) => ({
            companyId: value && value.length ? value[0].id : void 0,
          }),
        },
        {
          component: "Input",
          id: "contractName",
          label: messages("finance-6.key54") /*合同名称*/,
        },
        {
          component: "DateRangePicker",
          id: "dateRange",
          parser: (value) => ({
            signDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : null,
            signDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : null,
          }),
          label: messages("finance-6.key55") /*签署日期*/,
          dataIndex: "signDate",
        },
        {
          ...expensePartner,
          ...{ label: messages("finance-6.key58") /*合同方*/ },
        },
        {
          component: "Select",
          id: "currency",
          children: [],
          props: {
            style: { width: "100%" },
            showSearch: true,
            filterOption: (input, option) =>
              option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0,
          },
          label: messages("common.currency") /*币种*/,
          dataIndex: "currency",
        },
        {
          id: "numberRange",
          label: messages("finance-6.key80") /*金额范围*/,
          component: <NumberRange />,
          parser: (value) => ({
            amountFrom: value && value[0] ? value[0] : null,
            amountTo: value && value[1] ? value[1] : null,
          }),
          tagParser: (value) =>
            value &&
            (value[0] || value[1]) &&
            `${value[0] === 0 ? value[0] : value[0] || ""} ~ ${value[1] === 0 ? value[1] : value[1] || ""}`,
          dataIndex: "amount",
        },
        {
          component: "Input",
          id: "remark",
          label: messages("common.remark") /*备注*/,
        },
        {
          component: "RadioGroup",
          id: "status",
          label: messages("common.column.status") /*状态*/,
          children: this.statusList
            .filter((item) => item.value !== 6004)
            .map((item) => (
              <Radio key={item.value} value={item.value}>
                {item.label}
              </Radio>
            )),
          props: {
            placeholder: messages("finance-6.key81") /*请选择temp*/,
            style: { width: "100%" },
          },
          dataIndex: "status",
          initialValue: "all",
          tagParser: (value) => this.statusList.find((item) => item.value === value).label,
          parser: (value) => ({ status: value === "all" ? "" : value }),
          row: true,
        },
      ],
      searchParams: {},
      data: [],
      contractType: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
      },
      company: "",
      NewContract: menuRoute.getRouteItem("new-contract", "key"), //新建合同
      ContractDetail: menuRoute.getRouteItem("contract-detail", "key"), //合同详情
    };
    this.searchNumber = debounce(this.searchNumber, 500);
  }

  statusList = [
    { value: "all", label: messages("common.all") /*全部*/ },
    { value: 1001, label: messages("finance-6.key1") /*编辑中*/ },
    { value: 1002, label: messages("finance-6.key2") /*审批中*/ },
    { value: 1003, label: messages("common.withdraw") /*撤回*/ },
    { value: 1004, label: messages("finance-6.key3") /*审批通过*/ },
    { value: 1005, label: messages("finance-6.key4") /*审批驳回*/ },
    { value: 6001, label: messages("finance-6.key5") /*暂挂*/ },
    { value: 6002, label: messages("finance-6.key6") /*已取消*/ },
    { value: 6003, label: messages("finance-6.key7") /*已完成*/ },
    { value: 6004, label: messages("finance-6.key8") /*取消暂挂*/ },
  ];

  color = {
    default: "#55B1F2",
    processing: "#55B1F2",
    success: "#4DC690",
    error: "#FF6680",
    closed: "#B5C0CE",
    warning: "#F2C849",
  };

  columns = [
    {
      title: messages("finance-6.key46") /*合同编号*/,
      dataIndex: "contractNumber",
      width: 160,
      minWidth: 120,
      render: (desc) => (
        <Popover placement="topLeft" content={desc}>
          {desc ? desc : ""}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key47") /*原合同编码*/,
      dataIndex: "originContractNumber",
      width: 160,
      minWidth: 120,
      render: (desc) => (
        <Popover placement="topLeft" content={desc}>
          {desc ? desc : ""}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key79") /*合同类型*/,
      dataIndex: "contractTypeName",
      width: 160,
      minWidth: 120,
      render: (desc) => (
        <Popover placement="topLeft" content={desc}>
          {desc ? desc : ""}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key54") /*合同名称*/,
      width: 200,
      minWidth: 180,
      dataIndex: "contractName",
      render: (desc) => (
        <Popover placement="topLeft" content={desc}>
          {desc ? desc : ""}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key53") /*合同公司*/,
      dataIndex: "companyName",
      width: 240,
      minWidth: 180,
      render: (desc) => (
        <Popover placement="topLeft" content={desc}>
          {desc ? desc : ""}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key55") /*签署日期*/,
      dataIndex: "signDate",
      stableWidth: 120,
      render: (desc) => (
        <Popover placement="topLeft" content={moment(desc).format("YYYY-MM-DD")}>
          {desc ? moment(desc).format("YYYY-MM-DD") : "-"}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key82") /*类型 | 合同方*/,
      dataIndex: "partnerCategoryName",
      width: 240,
      minWidth: 180,
      render: (value, record) => {
        return value ? (
          <div>
            {value}
            <span className="ant-divider" />
            {record.partnerName}
          </div>
        ) : (
          "-"
        );
      },
    },
    {
      title: messages("common.currency") /*币种*/,
      dataIndex: "currency",
      stableWidth: 100,
      render: (desc) => (
        <Popover placement="topLeft" content={desc}>
          {desc ? desc : ""}
        </Popover>
      ),
    },
    {
      title: messages("finance-6.key83") /*合同金额*/,
      dataIndex: "amount",
      width: 160,
      minWidth: 140,
      render: (desc) => (
        <Popover placement="topLeft" content={this.filterMoney(desc, 2)}>
          {this.filterMoney(desc, 2)}
        </Popover>
      ),
    },
    {
      title: messages("common.column.status") /*状态*/,
      dataIndex: "status",
      stableWidth: this.props.language.code === "zh_cn" ? 100 : 180,
      render: (value) => <Tag color={this.color[contractStatus[value].state]}>{contractStatus[value].label}</Tag>,
    },
  ];

  componentDidMount() {
    Promise.all([this.getCurrencyList(), this.getContractType()]).finally(() => {});
  }

  //获取币种列表
  getCurrencyList = async () => {
    const { searchForm } = this.state;
    const ret = await baseService.getAllCurrencyByLanguage("zh_cn", this.props.user.userOID, true, false);
    searchForm.some((item) => {
      if (item.dataIndex === "currency") {
        item.children = ret.data.map((currency) => (
          <Option key={currency.currency}>
            {currency.currency} &nbsp;{currency.currencyName}
          </Option>
        ));
        return true;
      }
    });
    this.setState({ currencyList: ret.data, searchForm });
  };

  getContractType = async () => {
    const ret = await contractService.getContractTypeByCompany({
      companyId: this.props.company.id,
    });
    if (!ret.data[0]) {
      Modal.warning({
        title: messages("common.info") /*提示*/,
        content: messages("finance-6.key84") /*当前公司下无可用的合同类型，请联系管理员！*/,
      });
    }
    this.setState({ contractType: ret.data });
  };

  searchNumber = async (e) => {
    await this.setState({ contractNumber: e });
    await this.advancedTableRef.getList(true, 1);
  };

  //合同详情
  rowClick = (record) => {
    openSlideFrame.contractDetail(
      {
        entityOID: record.documentOid,
        entry: "maintain",
        id: record.id,
      },
      {
        afterClose: (value) => {
          typeof value === "boolean" && value && this.advancedTableRef.getList(true);
        },
      },
      this
    );
  };

  //新建
  handleCreate = (e) => {
    const item = e.key.split(",");
    this.context.router.push(
      this.state.NewContract.url.replace(":formOID", item[0]).replace(":contractTypeId", item[1])
    );
  };

  service = (size, page, params) => {
    const { contractNumber } = this.state;
    return contractService.getContractViewList(size, page, {
      ...params,
      contractNumber,
    });
  };

  render() {
    const { searchForm } = this.state;
    return (
      <div className="my-contract full-height-page">
        <AdvancedTable
          index
          title={messages("finance-6.key149") /*合同查看及维护*/}
          waterMark
          service={this.service}
          columns={this.columns}
          onRef={(ref) => (this.advancedTableRef = ref)}
          searchForm={searchForm}
          onRow={(record) => ({
            onClick: () => this.rowClick(record),
          })}
          rowKey="id"
          tableName="contract-list"
        >
          <div className="table-header" style={{ height: 28 }}>
            <Search
              className="input-search input-search-left"
              placeholder={messages("finance-6.key87") /*请输入合同编号/原合同编号*/}
              onChange={(value) => this.searchNumber(value.target.value)}
            />
          </div>
        </AdvancedTable>
      </div>
    );
  }
}

ContractView.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
  };
}

const wrappedContractView = Form.create()(ContractView);

export default connect(mapStateToProps, null, null, { withRef: true })(wrappedContractView);
